<template>
  <el-dialog
    v-model="isDialogShow"
    :title="title"
    width="500"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="form.longitude" type="number" />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="form.latitude" type="number" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <!-- <el-input v-model="form.phone" type="number" /> -->
        <el-select v-model="form.phone" placeholder="请选择电话号码" style="width: 100%">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" type="textarea" />
      </el-form-item>
      <el-form-item label="选择地址">
        <map-container @click-child="handleMapClickChild" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import { computed, ref, onMounted, reactive } from "vue";
import { ElForm, ElMessage } from "element-plus";
import { addMealCenter, getMealCenterById, updateMealCenter } from "@/api/mealCenter";
import { isAxiosError } from "axios";
import { MealCenterRequest } from "@/api/types/mealCenter";
import MapContainer from "@/components/MapContainer.vue";
import { getAccountList } from "@/api/account";

const props = defineProps<{ id?: number }>();
const emit = defineEmits<{
  addSuccess: [];
  success: [];
  updateSuccess: [];
}>();

const isDialogShow = defineModel<boolean>();

const title = computed(() => (props.id === undefined ? "添加出餐中心" : "修改出餐中心"));
const form = ref<MealCenterRequest>({});
const formRef = ref<InstanceType<typeof ElForm>>();
const rules = {
  address: [
    {
      required: true,
      message: "地址不能为空",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur",
    },
  ],
  latitude: [
    {
      required: true,
      message: "纬度不能为空",
      trigger: "blur",
    },
  ],
  longitude: [
    {
      required: true,
      message: "经度不能为空",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "电话不能为空",
      trigger: "blur",
    },
  ],
};

async function getData() {
  if (props.id !== undefined) {
    const { result } = await getMealCenterById(props.id);
    if (result !== undefined) {
      form.value = result[0];
    }
  }
}

// 定义接口以描述对象的形状
interface User {
  id: number;
  username: string;
}

const options = ref<User[]>([]);

function handleCancelClick() {
  isDialogShow.value = false;
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid) => {
    if (isValid) {
      try {
        if (props.id === undefined) {
          await addMealCenter(form.value);
          ElMessage.success("添加成功");
          emit("addSuccess");
        } else {
          await updateMealCenter(form.value);
          ElMessage.success("修改成功");
          emit("updateSuccess");
        }
        isDialogShow.value = false;
        emit("success");
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error("表单验证失败，请检查输入");
    }
  });
}

async function handleDialogClosed() {
  formRef.value?.resetFields();
}

async function handleDialogOpen() {
  await getData();
}

function handleMapClickChild({
  locationval,
  lng,
  lat,
}: {
  locationval: string;
  lng: string;
  lat: string;
}) {
  form.value.address = locationval;
  form.value.latitude = Number(lat);
  form.value.longitude = Number(lng);
}

onMounted(async () => {
  try {
    const res = await getAccountList();
    if (res.data) {
      res.data.info_list = res.data.info_list.filter((item) => {
        return item.username.length == 11;
      });
      options.value = res.data.info_list;
    } else {
      ElMessage.error("网络错误");
    }
  } catch (error) {
    console.error(error);
  }
});
</script>
